import { Chart } from '@antv/g2';
import { useEffect } from 'react';
import JSONEditor from "@/pages/antv/components/JSONEditorComponent";
import { useState } from 'react';
import { Button } from 'antd';

export default function antvPage() {
  const option = {
    x: "x",
    y: "y",
    data: [
      { x: 'A', y: 0.02782 },
      { x: 'B', y: 0.04253 },
      { x: 'C', y: 0.12702 },
      { x: 'D', y: 0.02288 },
      { x: 'E', y: 0.02015 },
      { x: 'F', y: 0.06094 },
      { x: 'G', y: 0.06966 },
      { x: 'H', y: 0.00153 },
      { x: 'I', y: 0.00772 },
      { x: 'J', y: 0.04025 },
      { x: 'K', y: 0.02406 },
      { x: 'L', y: 0.06749 },
      { x: 'M', y: 0.08167 },
      { x: 'N', y: 0.08167 },
      { x: 'O', y: 0.07507 },
      { x: 'P', y: 0.01929 },
      { x: 'Q', y: 0.00095 },
      { x: 'R', y: 0.05987 },
      { x: 'S', y: 0.06327 },
      { x: 'T', y: 0.09056 },
      { x: 'U', y: 0.02758 },
      { x: 'V', y: 0.00978 },
      { x: 'W', y: 0.0236 },
      { x: 'X', y: 0.0015 },
      { x: 'Y', y: 0.01974 },
      { x: 'Z', y: 0.00074 },
    ]
  }
  //let chart: any;
  let [data, setData] = useState(option);

  function showData() {
    // 初始化图表实例
    let chart = new Chart({
      container: 'container',
      autoFit: true,
    });
    chart
      .interval()
      .data({
        type: 'fetch',
        data: data.data,
        transform: [
          {
            type: 'filter',
            callback: (d: any) => d.year === 2000,
          },
        ],
      })
      .encode('x', data.x)
      .encode('y', (d: any) => (d.sex === 1 ? -d.people : d.people))
      .encode('color', 'sex')
      .scale('color', { type: 'ordinal' })
      .scale('x', { range: [1, 0] })
      .axis('y', { labelFormatter: '~s' })
      .legend('color', { labelFormatter: (d: any) => (d === 1 ? 'Male' : 'Female') })
      .tooltip((d) => ({ value: d.people, name: d.sex === 1 ? 'Male' : 'Female' }));


    // 渲染可视化
    chart.render();
  }


  // 准备数据
  useEffect(() => {
    showData()
    return () => {
      //chart.destroy();
    }
  }, [])

  return (
    <div>
      <div id="container" ></div>
      <Button onClick={() => {
        showData()
      }}> 提交 </Button>
      <JSONEditor option={data} onDataChange={(e) => {
        setData(e.json)
      }}></JSONEditor>
    </div>
  );
}

antvPage.route = {
  [MENU_TITLE]: "可交互柱形图",
  [MENU_PATH]: "/antv/g2/t6",
};
